#include <jni.h>
#include <string.h>
#include "./quickjs/quickjs.h"

extern "C" JNIEXPORT jstring JNICALL
Java_com_example_qjsandroid_MainActivity_executeQuickJS(
        JNIEnv *env,
        jobject /* this */,
        jstring jsCode) {
    const char *code = env->GetStringUTFChars(jsCode, nullptr);

    JSRuntime *runtime = JS_NewRuntime();
    JSContext *ctx = JS_NewContext(runtime);

    // 执行 JavaScript 代码
    JSValue result = JS_Eval(ctx, code, strlen(code), "<input>", JS_EVAL_TYPE_GLOBAL);

    // 获取结果
    const char *result_str = JS_ToCString(ctx, result);
    jstring output = env->NewStringUTF(result_str);

    // 释放资源
    JS_FreeCString(ctx, result_str);
    JS_FreeValue(ctx, result);
    JS_FreeContext(ctx);
    JS_FreeRuntime(runtime);

    env->ReleaseStringUTFChars(jsCode, code);

    return output;
}